/**
 * @filename:ReturnMaterialServiceImpl Dec 20, 2023
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2022 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.vtuzx.core.VtuzxException;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.domain.SysAdmin;
import com.wonder.admin.service.SysAdminService;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.ReturnMaterialDao;
import com.wonder.app.mapper.ReturnMaterialDetailDao;
import com.wonder.app.service.InventoryService;
import com.wonder.app.service.ReturnMaterialDetailService;
import com.wonder.app.service.ReturnMaterialService;
import com.wonder.app.request.ReturnMaterialRequest;
import com.wonder.bean.kingdee.xqc.BillMaterial;
import com.wonder.common.utils.DateUtils;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.common.AjaxResult;

import java.util.*;

import com.wonder.constant.BillEvent;
import com.wonder.constant.BillType;
import com.wonder.constant.IXqcConst;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;

/**   
 * @Description:TODO(生产退料单服务实现)
 *
 * @version: 1.1.0
 * @author: Wonder
 * 
 */
@Service
public class ReturnMaterialServiceImpl  extends ServiceImpl<ReturnMaterialDao, ReturnMaterial> implements ReturnMaterialService  {

	/**
	 * Logger
	 */
	private static final Logger _logger = LoggerFactory.getLogger(ReturnMaterialServiceImpl.class);

	@Autowired
	private ReturnMaterialDetailDao returnMaterialDetailDao;

	@Autowired
	private ReturnMaterialDao returnMaterialDao;

	@Autowired
	private InventoryService inventoryService;

	@Autowired
	private ReturnMaterialService returnMaterialService;

	@Autowired
	private ReturnMaterialDetailService returnMaterialDetailService;


    /**
     * 验证生产退料单信息
     * 
     * @param returnMaterial
     * @param type
     * @return String
     */
    @Override
    public String validate(ReturnMaterial returnMaterial,String type){
    
    
       return "";
    }
    
    
    /**
	 * Description:生产退料单分页返回
	 * @param request //检索条件
	 * @param page //分页参数
	 * @return IPage<ReturnMaterial>   //分页记录
	 */
	@Override 
	public IPage<ReturnMaterial> selectList(ReturnMaterialRequest request, Page<ReturnMaterial> page){
	    LambdaQueryWrapper<ReturnMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
	    
	    if (null != request.getId()) {
	       lambdaQueryWrapper.eq(ReturnMaterial::getId, request.getId());
	      }               
             
        if (null != request.getBillNo()) {
			    lambdaQueryWrapper.like(ReturnMaterial::getBillNo, request.getBillNo()); 
		    }

		if (null != request.getTaskBillNo()) {
			lambdaQueryWrapper.like(ReturnMaterial::getTaskBillNo, request.getTaskBillNo());
		}
		if (request.getCreateTime() != null){
        	Date[] createTime=request.getCreateTime();
        	if(createTime.length>0)
        	  lambdaQueryWrapper.ge(ReturnMaterial::getCreateTime, createTime[0]); 
        	if(createTime.length==2)
        	  lambdaQueryWrapper.le(ReturnMaterial::getCreateTime, DateUtils.dateToStr(createTime[1],"yyyy-MM-dd")+ " 23:59:59");
        	
        }    
             
        
		lambdaQueryWrapper.orderByDesc(ReturnMaterial::getId);	
		Page<ReturnMaterial> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
		return selectPage;
    }

	@Override
	public VtuzxMap getReturnDetail(Long id) {
		ReturnMaterial returnMaterial = returnMaterialDao.selectById(id);
		List<ReturnMaterialDetail> detailList = returnMaterialDetailDao.selectList(new QueryWrapper<ReturnMaterialDetail>().eq("entryId", id));
		return new VtuzxMap("header",returnMaterial)
				.append("dataList",detailList);
	}

	@Override
	public boolean unAuditReturnMaterial(Long user_id, String userName, Long id) {
		ReturnMaterial returnMaterial = returnMaterialDao.selectById(id);
		returnMaterial.setUpdateTime(new DateTime());
		returnMaterial.setUpdateUserName(userName);
		returnMaterial.setStatus("unAudit");
		String billNo = returnMaterial.getBillNo();

		//反审需要把入库的库存扣减掉
		List<ReturnMaterialDetail> detailList = returnMaterialDetailDao.selectList(new QueryWrapper<ReturnMaterialDetail>()
				.eq("entryId", id));

		List<BillMaterial> dataList = new ArrayList<>();//需要增加的库存
		for (ReturnMaterialDetail data : detailList) {
			BillMaterial material = new BillMaterial();
			material.setMaterialNo(data.getMaterialNo());
			material.setMaterialName(data.getMaterialName());
			material.setMaterialModel(data.getSpecification());
			material.setCount(data.getCount());
			material.setStockNo(data.getStockNo());
			material.setBatchNo(data.getFlot());
			material.setUnit(data.getUnit());
			material.setProduceDate(data.getProduceDate());
			material.setExpiryDate(data.getExpiryDate());
			material.setProduce(data.getIsProduce());
			material.setFlot(data.getIsFlot());
			dataList.add(material);
		}
		try {
			Map<String, Object> stringObjectMap = inventoryService.reduceInventory(user_id, userName, BillEvent.Unaudit, BillType.SCTL, billNo, dataList);
			if (!(Boolean) stringObjectMap.get("status")){
				return false;
			}
		} catch (Exception e){
			_logger.info(e.getMessage());
		}

		boolean isSuccess = returnMaterialService.updateById(returnMaterial);

		return isSuccess;
	}

	@Override
	public boolean auditReturnMaterial(Long user_id, String userName, Long id) {
		ReturnMaterial returnMaterial = returnMaterialDao.selectById(id);
		returnMaterial.setUpdateTime(new DateTime());
		returnMaterial.setUpdateUserName(userName);
		returnMaterial.setStatus("audit");
		returnMaterial.setAuditTime(new DateTime());
		returnMaterial.setAuditUserName(userName);
		String billNo = returnMaterial.getBillNo();
		//审核订单需要扣减库存
		List<ReturnMaterialDetail> detailList = returnMaterialDetailDao.selectList(new QueryWrapper<ReturnMaterialDetail>()
				.eq("entryId", id));

		List<BillMaterial> dataList = new ArrayList<>();//需要扣减的库存
		for (ReturnMaterialDetail data : detailList) {
			BillMaterial material = new BillMaterial();
			material.setMaterialNo(data.getMaterialNo());
			material.setMaterialName(data.getMaterialName());
			material.setMaterialModel(data.getSpecification());
			material.setCount(data.getCount());
			material.setStockNo(data.getStockNo());
			material.setBatchNo(data.getFlot());
			material.setUnit(data.getUnit());
			material.setProduceDate(data.getProduceDate());
			material.setExpiryDate(data.getExpiryDate());
			material.setProduce(data.getIsProduce());
			material.setFlot(data.getIsFlot());
			dataList.add(material);
		}
		try {
			Map<String, Object> stringObjectMap = inventoryService.addInventory(user_id, userName, BillEvent.Audit, BillType.SCTL, billNo, dataList);
			if (!(Boolean) stringObjectMap.get("status")){
				return false;
			}

		} catch (Exception e){
			_logger.info(e.getMessage());

		}

		boolean isSuccess = returnMaterialService.updateById(returnMaterial);

		return isSuccess;
	}

	@Override
	public boolean saveReturnMaterial(String userName, Map<String, Object> header, List<Map<String, Object>> dataList) {
		List<ReturnMaterialDetail> detailList = new ArrayList<>();
		double sumCount = 0;
		for (Map<String,Object> map : dataList) {
			ReturnMaterialDetail detail = new ReturnMaterialDetail();
			detail.setId(VtuzxUtil.getLong(map,"id"));
			detail.setBillNo(VtuzxUtil.getString(map,"billNo"));
			detail.setMaterialNo(VtuzxUtil.getString(map,"materialNo"));
			detail.setMaterialName(VtuzxUtil.getString(map,"materialName"));
			detail.setSpecification(VtuzxUtil.getString(map,"specification"));
			detail.setFlot(VtuzxUtil.getString(map,"flot"));
			detail.setProduceDate(VtuzxUtil.parseDate(VtuzxUtil.getString(map,"produceDate")));
			detail.setExpiryDate(VtuzxUtil.parseDate(VtuzxUtil.getString(map,"expiryDate")));
			detail.setUnit(VtuzxUtil.getString(map,"unit"));
			detail.setStockNo(VtuzxUtil.getString(map,"stockNo"));
			detail.setTaskBillNo(VtuzxUtil.getString(map,"taskBillNo"));
			detail.setCount(VtuzxUtil.getDouble(map,"count"));
			detail.setIsProduce(VtuzxUtil.getBoolean(map,"isProduce"));
			detail.setIsFlot(VtuzxUtil.getBoolean(map,"isFlot"));
			detail.setUpdateUserName(userName);
			detail.setUpdateTime(new DateTime());
			detailList.add(detail);
			sumCount += VtuzxUtil.getDouble(map,"count");
		}
		//修改外层的数量
		Long id = Long.parseLong(header.get("id").toString());
		ReturnMaterial returnMaterial = returnMaterialDao.selectById(id);
		returnMaterial.setCount(sumCount);
		returnMaterial.setStatus("save");
		boolean pickRes = returnMaterialService.updateById(returnMaterial);
		boolean res = returnMaterialDetailService.saveOrUpdateBatch(detailList);
		return res && pickRes;
	}

	@Override
	public Boolean saveReturnMaterialPad(JSONObject map) {
		String taskBillNo = map.getStr("taskBillNo");
		String userName = map.getStr("userName");
		Long userId = map.getLong("userId");
		String source = map.getStr("source");
		JSONArray jsonArray = map.getJSONArray("material");//物料信息
		List<ReturnMaterialDetail> detailList = new ArrayList<>();

		String billNo = IXqcConst.createBillNo(BillType.SCTL);
		double sumCount = 0;//外层表总数
		for (int i = 0;i < jsonArray.size(); i++ ) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			String materialNo = jsonObject.getStr("materialNo");
			String materialName = jsonObject.getStr("materialName");
			String specification = jsonObject.getStr("specification");
			String stockNo = jsonObject.getStr("stockNo");
			String batchNo = jsonObject.getStr("batchNo");
			String unit = jsonObject.getStr("unit");
			double count = jsonObject.getDouble("count");
//			String source = jsonObject.getStr("source");//退料来源1生产领料0生产补料
			String sourceNo = jsonObject.getStr("sourceNo");//来源单号
			String produceDate = jsonObject.getStr("produceDate");
			String expiryDate = jsonObject.getStr("expiryDate");

			ReturnMaterialDetail detail = new ReturnMaterialDetail();
			//判断有没有启用批次和保质期
			if (!VtuzxUtil.isEmpty(batchNo)){
				detail.setIsFlot(true);
				detail.setFlot(batchNo);
			} else {
				detail.setIsFlot(false);
			}
			if (!VtuzxUtil.isEmpty(produceDate)){
				detail.setIsProduce(true);
				detail.setProduceDate(VtuzxUtil.parseDate(produceDate));
				detail.setExpiryDate(VtuzxUtil.parseDate(expiryDate));
			} else {
				detail.setIsProduce(false);
			}
			detail.setBillNo(billNo);
			detail.setMaterialNo(materialNo);
			detail.setMaterialName(materialName);
			detail.setSpecification(specification);
			detail.setUnit(unit);
			detail.setStockNo(stockNo);
			detail.setSourceNo(sourceNo);
			detail.setSource(source);
			detail.setCreateUserName(userName);
			detail.setCreateUserId(userId);
			detail.setCount(count);
			detail.setUpdateUserName(userName);
			detail.setTaskBillNo(taskBillNo);
			sumCount += count;
			detailList.add(detail);
		}
		//外层表数据
		ReturnMaterial returnMaterial = new ReturnMaterial();
		returnMaterial.setStatus("unAudit");
		returnMaterial.setBillNo(billNo);
		returnMaterial.setCount(sumCount);
		returnMaterial.setCreateUserId(userId);
		returnMaterial.setCreateUserName(userName);
		returnMaterial.setTaskBillNo(taskBillNo);
		returnMaterial.setUpdateUserName(userName);
		returnMaterial.setSource(source);
		boolean save = returnMaterialService.save(returnMaterial);
		Long id = returnMaterial.getId();
		for (ReturnMaterialDetail detail : detailList) {
			detail.setEntryId(id);
		}
		boolean detailRes = returnMaterialDetailService.saveBatch(detailList);
		return save && detailRes;
	}


}